var url = window.location.href; // 获取完整的URL  
var searchParams = new URLSearchParams(window.location.search); // 获取URL中的参数部分  
uid = searchParams.get("uid");
// 获取初始数据
$.ajax({
    url: '/noinfo/update_watch_get/',
    type: 'GET',
    async: false,
    dataType: 'json',
    data: {
        'id': uid,
    },
    success: function(data) {
        watch = JSON.parse(data.watch)[0].fields;
        $("input[name='type']").each(function() {
            if ($(this).val() == watch.type) {
              $(this).prop("checked", true);
            } else {
              $(this).prop("checked", false);
            }
          });
        $.each(watch, function(key, value) {
            if (key != 'type' && key !='create_time' && key !='update_time' && key !='code' && key !='status') {
                $('#' + key).val(value); 
            }
        });
        var type = $("input[name='type']:checked").val();
        var times = $('#times').val();
        updateOpt(times, type);
        $('#status').val(watch.status);
    }
});

$('#times').change(function() {
    var type = $("input[name='type']:checked").val();
    var times = $('#times').val();
    updateOpt(times, type);
});  

// 清除并批量添加option选项
function updateOption(selectId, texts) {
    $('#' + selectId).empty();
    $.each(texts, function(index, text) {
        var option = $('<option>').text(text);
        $('#' + selectId).append(option);
    });
    $('#' + selectId).val(null);
}

function updateOpt(times, type) {
    if(times=='1') {
        if(type=='动画') {
            var option = ['追番', '完结补番', '老番入坑'];
        } else if(type=='电影') {
            var option = ['影院', '网络首发', '院线下映', '老作新看'];
        } else {
            var option = ['追更', '完结爽看', '老作新看'];
        }
    } else {
        var option = ['续作回顾', '系列回看'];
    }
    updateOption('status', option);
};

// 提交数据
$('#submit').click(function() {
    var type = $("input[name='type']:checked").val();
    var name = $("#name").val();
    var times = $("#times").val();
    var date_watch_start = $("#date_watch_start").val();
    var date_watch_end = $("#date_watch_end").val();
    var status = $("#status").val();
    // 发送AJAX请求
    $.ajax({
        url: '/noinfo/update_watch_post/',
        type: 'POST',
        dataType: 'json',
        data: { 
            id: uid,
            type: type,
            name: name,
            times: times,
            date_watch_start: date_watch_start,
            date_watch_end: date_watch_end,
            status: status,
        },
        success: function(data) {
            if(data.code == 'success') {
                alert(name+' 修改完成');
                location.reload();
            } else {
                alert(data.code);
            }  
        },
        error: function(xhr, status, error) {
            alert('ajax执行失败');
          }
        });
})